import axios from 'axios'
// import errorCode from '@/utils/errorCode'
import { Notification, MessageBox, Message, Loading } from 'element-ui'
import { saveAs } from 'file-saver'
import { blobValidate } from "@/utils/http"
let downloadLoadingInstance;
const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    // baseURL:'/localApi',
    baseURL:'http://pis.aacitybus.gov.et/7777/', 
    // baseURL:'http://localhost:7777',
    // 超时
    timeout: 600000
  })
// 通用下载方法 post请求
// export function download(url, params, filename) {
//     downloadLoadingInstance = Loading.service({ text: "Downloading data, please wait", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
//     return service.post(url, params, {
//       headers: { 'Content-Type': 'application/json;charset=utf-8' },
//       responseType: 'blob'
//     }).then(async (data) => {
//       const isLogin = await blobValidate(data);
//       if (isLogin) {
//         const blob = new Blob([data])
//         saveAs(blob, filename)
//       } else {
//         const resText = await data.text();
//         const rspObj = JSON.parse(resText);
//         const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default'] || rspObj.message
//         Message.error(errMsg);
//       }
//       downloadLoadingInstance.close();
//     }).catch((r) => {
//       console.error(r)
//       // Message.error('下载文件出现错误，请联系管理员！')
//       Message.error('Error downloading file, please contact the administrator!')
//       downloadLoadingInstance.close();
//     })
//   }
  
  // 通用下载方法 get请求
  export function downloadGet(url, params, filename) {
    downloadLoadingInstance = Loading.service({ text: "Downloading data, please wait", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
    return service.get(url, {
      headers: { 'Content-Type': 'application/json;charset=utf-8' },
      responseType: 'blob',
      params: params
    }).then(async (data) => {
        console.log(data);
        const blob = new Blob([data.data], {type: 'text/plain;charset=utf-8'})
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob);
        link.download = decodeURI(data.headers['content-disposition'].split(';')[1].split('filename=')[1])
        document.body.appendChild(link)
        link.click()
        downloadLoadingInstance.close();
    }).catch((r) => {
      console.error(r)
      // Message.error('下载文件出现错误，请联系管理员！')
      Message.error('Error downloading file, please contact the administrator!')
      downloadLoadingInstance.close();
    })
  }
  export default service